package cn.edu.seig.himusic.minio;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;

public class MinioPublicPolicyExample {

  static void createBucketIfNotExist(MinioClient minioClient, String bucketName) {
    try {
      // 创建 bucket（如果不存在）
      boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
      if (!found) {
        minioClient.makeBucket(
            MakeBucketArgs.builder()
                .bucket(bucketName)
                .build()
        );
        System.out.println("✅ Bucket " + bucketName + " 创建成功！");
      } else {
        System.out.println("⚠️ Bucket " + bucketName + " 已存在。");
      }

    } catch (Exception e) {
      System.err.println("❌ 创建 bucket 出错: " + e.getMessage());
    }
  }

  static void initBucket() throws Exception {
    // 创建客户端
    MinioClient minioClient =
        MinioClient.builder()
            .endpoint("http://localhost:9000") // MinIO 服务地址
            .credentials("minioadmin", "minioadmin") // 账号密码
            .build();
    String bucketName = "vibe-music-data";

    createBucketIfNotExist(minioClient, bucketName);

    // 定义公共访问策略（允许匿名用户 GetObject）
    String policy = """
        {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": "*",
                    "Action": [
                        "s3:GetObject"
                    ],
                    "Resource": [
                        "arn:aws:s3:::%s/*"
                    ]
                }
            ]
        }
        """.formatted(bucketName);

    // 设置 bucket 策略
    minioClient.setBucketPolicy(
        SetBucketPolicyArgs.builder()
            .bucket(bucketName)
            .config(policy)
            .build()
    );

    System.out.println("成功将 " + bucketName + " 设置为 public 访问！");

  }

  public static void main(String[] args) throws Exception {
    System.out.println("## start ##");
    initBucket();
    return;
  }
}
